// ignore_for_file: prefer_const_constructors
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_library/app/themes/app_colors.dart';
import 'package:flutter_base_library/index.dart';
import 'package:get/get.dart';
import 'package:safe_manage/config/my_app_data.dart';
import 'package:safe_manage/config/my_app_routes.dart';
import 'package:safe_manage/models/index.dart';
import 'package:safe_manage/pages/alarm/alarm_page/alarm_controller.dart';

class AlarmTypeListController extends GetxController {
  int type = 0;
  String url = "/safety-web/smokeRecord/page";
  String? sjlx;
  var title = "".obs;
  int currentPage = 1;
  var dataList = <CommonRecord>[].obs;
  var departmentList = <Department>[];
  int departmentFirstIndex = -1;
  int departmentSecondIndex = -1;
  int sfcl = -1; // 处理状态 0未处理 1已处理 2误报
  int sjsj = 0; // 开始时间，单位毫秒
  int cjsj = 0; // 结束时间，单位秒
  RefreshController refreshController = RefreshController();
  void onRefresh() {
    refreshController.resetNoData();
    currentPage = 1;
    _getDataFromNet();
  }

  void onLoading() {
    currentPage++;
    _getDataFromNet();
  }

  @override
  void onInit() {
    super.onInit();
    Map p = Get.parameters;
    type = int.tryParse(p["type"]) ?? 0;
    AlarmTypeModel argument = Get.arguments;
    url = argument.url;
    title.value = argument.title;
    sjlx = argument.sjlx;
    _getDataFromNet();
  }

  void _getDataFromNet() {
    Map p = {
      "cjyhid": MyAppData.instance.currentUser?.id,
      "gsid": MyAppData.instance.currentUser?.gsid,
    };
    if (departmentSecondIndex != -1 && departmentSecondIndex != -1) {
      Department department = departmentList[departmentFirstIndex];
      var children = department.children;
      if (children is List) {
        var child = children[departmentSecondIndex];
        if (child is Map) {
          var value = child['value'];
          p['cjbmid'] = value;
        }
      }
    }
    if (sfcl != -1) {
      p["sfcl"] = sfcl;
    }
    if (sjsj > 0 && cjsj > 0) {
      p['cjsj'] = sjsj;
      p['xgsj'] = cjsj;
    }
    if (sjlx != null && sjlx!.isNotEmpty) {
      p['sjlx'] = sjlx;
    }
    HttpUtils.post(
      url,
      body: {
        "current": currentPage,
        "size": 10,
        "parameter": p,
      },
      success: (result) {
        if (refreshController.isRefresh) {
          refreshController.refreshCompleted();
          dataList.clear();
        } else {
          refreshController.loadComplete();
        }
        var data = result['data'];
        if (data is Map) {
          int pages = data['pages'];
          int current = data['current'];
          if (current >= pages) {
            refreshController.loadNoData();
          }
          var records = data['records'];
          if (records is List) {
            for (var element in records) {
              dataList.add(CommonRecord.fromJson(element));
            }
          }
        }
        update();
      },
      fail: (errorMsg) {
        refreshController.loadFailed();
      },
    );
  }

  Future _getCascaderList() {
    if (departmentList.isNotEmpty) {
      return Future(() => null);
    }
    return HttpUtils.post(
      '/safety-web/department/getCascaderList',
      body: {
        "parameter": {
          // "id": MyAppData.instance.currentUser?.id,
          "gsid": MyAppData.instance.currentUser?.gsid,
        }
      },
      success: (result) {
        var data = result["data"];
        if (data is List) {
          departmentList.clear();
          for (var element in data) {
            departmentList.add(Department.fromJson(element));
          }
        }
      },
      fail: (errorMsg) {},
    );
  }

  void select1Clicked(BuildContext context) {
    _getCascaderList().then(
      (value) {
        var entity = BrnPickerEntity(
          children: List.generate(
            departmentList.length,
            (index) {
              Department department = departmentList[index];
              return BrnPickerEntity(
                value: department.value.toString(),
                name: department.label ?? "",
                isSelected: index == departmentFirstIndex,
                children: List.generate(
                  department.children?.length ?? 0,
                  (index) {
                    Map child = department.children![index];
                    return BrnPickerEntity(
                      value: child["value"].toString(),
                      name: child["label"],
                      isSelected: index == departmentSecondIndex,
                      type: "radio",
                    );
                  },
                ),
              );
            },
          ),
        );
        var selectionMenuView = BrnMultiColumnPicker(
          showSelectedCount: true,
          pickerTitleConfig: BrnPickerTitleConfig(
            titleContent: "请选择所在部门",
          ),
          entity: entity,
          defaultFocusedIndexes: [
            departmentFirstIndex,
            departmentSecondIndex,
            -1
          ],
          onConfirm: (Map<String, List<BrnPickerEntity>> results,
              int? firstIndex, int? secondIndex, int? thirdIndex) {
            departmentFirstIndex = firstIndex ?? -1;
            departmentSecondIndex = secondIndex ?? -1;
            refreshController.requestRefresh();
          },
        );
        showModalBottomSheet(
          context: context,
          builder: (dialogContext) {
            return selectionMenuView;
          },
        );
      },
    );
  }

  void select2Clicked(BuildContext context) {
    List<BrnMultiSelectBottomPickerItem> items = [];
    items.add(
      BrnMultiSelectBottomPickerItem("100", "未处理", isChecked: sfcl == 0),
    );
    items.add(
      BrnMultiSelectBottomPickerItem("101", "已处理", isChecked: sfcl == 1),
    );
    items.add(
      BrnMultiSelectBottomPickerItem("102", "误报", isChecked: sfcl == 2),
    );
    BrnMultiSelectListPicker.show(
      context,
      items: items,
      pickerTitleConfig: const BrnPickerTitleConfig(
        titleContent: "选择处理状态",
      ),
      onSubmit: (List<BrnMultiSelectBottomPickerItem> data) {
        Get.back();
      },
      onItemClick: (_, index) {
        if (sfcl != -1) {
          items[sfcl].isChecked = false;
        }
        sfcl = index;
        Get.back();
        refreshController.requestRefresh();
      },
      // onCancel: () {
      //   sfcl = -1;
      //   Get.back();
      //   refreshController.requestRefresh();
      // },
    );
  }

  void select3Clicked(BuildContext context) async {
    DateTimeRange? initialDateRange;
    if (sjsj > 0 && cjsj > 0) {
      DateTime start = DateTime.fromMillisecondsSinceEpoch(sjsj * 1000);
      DateTime end = DateTime.fromMillisecondsSinceEpoch(cjsj * 1000);
      initialDateRange = DateTimeRange(start: start, end: end);
    }
    //显示时间选择器
    showDateRangePicker(
      context: context,
      //初始的时间范围选择
      initialDateRange: initialDateRange,
      // 可以选择的开始时间
      firstDate: DateTime(2020, 1),
      //可以选择的结束时间
      lastDate: DateTime.now(),
      initialEntryMode: DatePickerEntryMode.calendar,
      builder: (context, child) {
        return Theme(
          data: ThemeData(
            appBarTheme: const AppBarTheme(
              backgroundColor: AppColors.kPrimaryColor,
            ),
          ),
          child: child ?? Container(),
        );
      },
    ).then((value) {
      if (value is DateTimeRange) {
        sjsj = value.start.millisecondsSinceEpoch ~/ 1000;
        cjsj = value.end.millisecondsSinceEpoch ~/ 1000;
        refreshController.requestRefresh();
      }
    });
  }

  void resetButtonClicked() {
    departmentSecondIndex = -1;
    departmentFirstIndex = -1;
    sfcl = -1; // 处理状态 0未处理 1已处理 2误报
    sjsj = 0; // 开始时间，单位毫秒
    cjsj = 0; // 结束时间，单位秒
    refreshController.requestRefresh();
  }

  void itemClicked(int index) {
    Get.toNamed(
      MyAppRoutes.alarmInfo,
      arguments: dataList[index],
      parameters: {
        "type": type.toString(),
        "sjlx": sjlx!,
      },
    )?.then((value) {
      refreshController.requestRefresh();
    });
  }
}
